package com.zzh.netty.nio;
/**
 * @ClassName NioSelectorServer
 * @date 2021/1/28 22:20
 * @Version 1.0
 * @Description
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 *@ClassName NioSelectorServer
 *@date 2021/1/28 22:20
 *@Version 1.0
 *@Description //
 */
public class NioSelectorServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //打开selector处理器
        Selector selector = Selector.open();

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("服务启动成功!");

        while (true) {
            //阻塞需要等待处理的事件发生  rdlist  epoll_ctl  epoll_create  epoll_wait
            selector.select();
            //获取selectkey中注册的全部事件进行处理
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    SocketChannel socketChannel = server.accept();
                    socketChannel.configureBlocking(false);
                    //这里只注册了读事件，如果需要给客户端发送数据可以注册写事件
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    System.out.println("客户端连接成功...");
                } else if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int len = socketChannel.read(byteBuffer);
                    if (len >0) {
                        System.out.println("接收到消息："+new String(byteBuffer.array()));
                    } else if(len == -1){
                        System.out.println("客户端断开连接");
                        socketChannel.close();
                    }
                }
                //从事件集合中移除本次处理的key，防止下次select重复处理
                iterator.remove();
            }
        }
    }
}
